package com.example.demo.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.example.demo.config.MqttBroker;
import com.example.demo.entity.*;
import com.example.demo.service.*;
import com.example.demo.util.GetMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api/code")
@RequiredArgsConstructor
@Component
public class CodeHistoryController {
    @Value("${codeSystem.ip}")
    private String ip;
    private  final CodeHistoryService codeHistoryService;
    private  final CodeAssociationService codeAssociationService;
    private  final CodeAssignmentRulesService codeAssignmentRulesService;
    private  final UserProductinfoService userProductinfoService;
    private final TrainInfoService trainInfoService;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/pack1")
    public GetMessage packCode (Integer ruleId, String userId, String appId, String trainingId,String codeList,Integer productInfoId) throws MqttException, JsonProcessingException {
        //String code=userProductinfoService.selectById(productInfoId).getCategorycode();
        String code = "";
        if(appId.equals("lcdPack")){
            code="MA.156.110116.1007/10.18003000";
        }else if(appId.equals("tvPack")){
            code="MA.156.110116.1007/10.18014000";
        }else{
            code="MA.156.110116.1007/10.18014000";
        }
        CodeHistory codeHistory1=new CodeHistory();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String formattedDate = now.format(formatter);
        code=code+formattedDate;
//        do {
//            CodeAssignmentRules codeAssignmentRules=codeAssignmentRulesService.selectById(ruleId);
//
//            String lastCode=codeHistoryService.makeCode(codeAssignmentRules.getCodingid());
//            if(lastCode==null){
//                return new GetMessage("失败","500",null);
//
//            }
//            code=code+"/"+lastCode;
//            codeHistory1=codeHistoryService.selectByCodeInfo(code);
//        } while (codeHistory1 != null);

        //String userId=token;
        CodeHistory codeHistory=new CodeHistory();
        codeHistory.setCodeinfo(code);
        codeHistory.setRulesid(ruleId);
        codeHistory.setTrainingid(trainingId);
        codeHistory.setUserid(userId);
        codeHistory.setAppid(appId);
        codeHistory.setProductinfoid(productInfoId);
        codeHistory.setRuletype(1);
        codeHistoryService.save(codeHistory);

        CodeAssociation codeAssociation=new CodeAssociation();
        codeAssociation.setCodeinfo(code);
        codeAssociation.setAssociationcode(codeList);
        codeAssociation.setAppid(appId);
        codeAssociation.setTrainingid(trainingId);
        codeAssociation.setUserid(userId);

        codeAssociationService.save(codeAssociation);

//        Map<String,Object> map=new HashMap<>();
//        map.put("data",code);
//        map.put("trainingId",trainingId);
//        String payload = objectMapper.writeValueAsString(map);
//        MqttBroker.mqttClient.publish("SendCode/"+appId+"/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));
        return new GetMessage("成功","200",code);
    }
    public GetMessage getCode(String userId,String trainingId,String appId,Integer ruleId) throws JsonProcessingException {
        String code="";
        TrainInfo trainInfo=trainInfoService.selectByUserId(userId).get(0);
        Map<String,String> headerList=new HashMap<>();
        headerList.put("X-Access-Key",trainInfo.getAccesskey());

        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("count", 1);

        CodeAssignmentRules codeAssignmentRules=codeAssignmentRulesService.selectById(ruleId);

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(jsonMap);
        String res=Util.postUrl(ip+"/api/client/identification-code-record/"+codeAssignmentRules.getRuleid()+"/batch",headerList,jsonString);

        JSONObject jsonResponse = new JSONObject(res);
        if(jsonResponse.get("code").equals("SUCCESS")){
            JSONObject data = new JSONObject(jsonResponse.get("data"));
            JSONArray jsonArray=new JSONArray(data.get("codes"));
            code=jsonArray.get(0).toString();
            CodeHistory codeHistory=new CodeHistory();
            codeHistory.setCodeinfo(code);
            codeHistory.setRulesid(ruleId);
            codeHistory.setTrainingid(trainingId);
            codeHistory.setUserid(userId);
            codeHistory.setAppid(appId);
            codeHistory.setRuletype(1);
            codeHistoryService.save(codeHistory);

            return new GetMessage("成功","200",code);
        }
        return new GetMessage(jsonResponse.get("message").toString(),"500","");
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/pack")
    public GetMessage packCode1 (Integer ruleId, String userId, String appId, String trainingId,String codeList,Integer productInfoId) throws MqttException, JsonProcessingException {
        //赋码
        GetMessage mes5= getCode(userId,trainingId,appId,ruleId);
        if(!(mes5.getCode().equals("200"))){
            return mes5;
        }
        String code=mes5.getData().toString();

        CodeHistory codeHistory=new CodeHistory();
        codeHistory.setCodeinfo(code);
        codeHistory.setRulesid(ruleId);
        codeHistory.setTrainingid(trainingId);
        codeHistory.setUserid(userId);
        codeHistory.setAppid(appId);
        codeHistory.setProductinfoid(productInfoId);
        codeHistory.setRuletype(1);
        codeHistoryService.save(codeHistory);

        CodeAssociation codeAssociation=new CodeAssociation();
        codeAssociation.setCodeinfo(code);
        codeAssociation.setAssociationcode(codeList);
        codeAssociation.setAppid(appId);
        codeAssociation.setTrainingid(trainingId);
        codeAssociation.setUserid(userId);

        codeAssociationService.save(codeAssociation);

        return new GetMessage("成功","200",code);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/select")
    public GetMessage select ( String userId, String appId, String trainingId){
        //String userId=token;
        List<CodeHistory> list=codeHistoryService.select(userId,appId,trainingId);
        return new GetMessage("成功","200",list);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/selectcode")
    public GetMessage selectcode ( String userId, String appId, String trainingId){
        //String userId=token;
        List<CodeHistory> list=codeHistoryService.select(userId,appId,trainingId);
        List<String> list1=new ArrayList<>();
        for (CodeHistory c: list) {
            list1.add(c.getCodeinfo());
        }
        return new GetMessage("成功","200",list1);
    }

    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/make1")
    public GetMessage get ( String userId, String appId, String trainingId,Integer ruleId,Integer num,Integer productInfoId) throws JsonProcessingException, MqttException {

        //String code=userProductinfoService.selectById(productInfoId).getCategorycode();
        String code = "";
        if(appId.equals("lcdPack")){
            code="MA.156.110116.1007/10.18003000";
        }else if(appId.equals("tvPack")){
            code="MA.156.110116.1007/10.18014000";
        }else if(appId.equals("tv")){
            code="MA.156.110116.1007/61.12000000.003";
        }else{
            code="MA.156.110116.1007/61.12000000.003";
        }
        List<String> codeList=new ArrayList<>();
        for(int i=0;i<num;i++){
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            String lastCode = now.format(formatter);
//            CodeAssignmentRules codeAssignmentRules=codeAssignmentRulesService.selectById(ruleId);
//            String lastCode=codeHistoryService.makeCode(codeAssignmentRules.getCodingid());
//            if(lastCode==null){
//                return new GetMessage("失败","500",null);
//
//            }
            codeList.add(code+"/"+lastCode);
            CodeHistory codeHistory=new CodeHistory();
            codeHistory.setCodeinfo(code+"/"+lastCode);
            codeHistory.setRulesid(ruleId);
            codeHistory.setTrainingid(trainingId);
            codeHistory.setUserid(userId);
            codeHistory.setAppid(appId);
            codeHistory.setRuletype(0);
            codeHistory.setProductinfoid(productInfoId);
            codeHistoryService.save(codeHistory);
        }
//        Map<String,Object> map=new HashMap<>();
//        map.put("data",codeList);
//        map.put("trainingId",trainingId);
//        String payload = objectMapper.writeValueAsString(map);
//        MqttBroker.mqttClient.publish("SendCode/"+appId+"/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));
        return new GetMessage("成功","200",codeList);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/make")
    public GetMessage make ( String userId, String appId, String trainingId,Integer ruleId,Integer num,Integer productInfoId) throws JsonProcessingException, MqttException {

        //赋码
        GetMessage mes5= getCode(userId,trainingId,appId,ruleId);
        if(!(mes5.getCode().equals("200"))){
            return mes5;
        }
        String code=mes5.getData().toString();
        List<String> codeList=new ArrayList<>();
        for(int i=0;i<num;i++){
            codeList.add(code);
            CodeHistory codeHistory=new CodeHistory();
            codeHistory.setCodeinfo(code);
            codeHistory.setRulesid(ruleId);
            codeHistory.setTrainingid(trainingId);
            codeHistory.setUserid(userId);
            codeHistory.setAppid(appId);
            codeHistory.setRuletype(0);
            codeHistory.setProductinfoid(productInfoId);
            codeHistoryService.save(codeHistory);
        }
        return new GetMessage("成功","200",codeList);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/preview")
    public GetMessage previewCode ( String userId, String appId, Integer ruleId) throws JsonProcessingException, MqttException {
        //String userId=token;
        String code="MA.156.110116.1007/61.12000000";
//        if(appId.equals("lingda")){
//            code="MA.156.110116.1007/10.18003000";
//        }else if(appId.equals("gree")){
//            code="MA.156.110116.1007/10.18014000";
//        }else{
//            code="MA.156.110116.1007/61.12000000";
//        }

        String lastCode=codeHistoryService.makeCode(ruleId);
        if(lastCode==null){
            return new GetMessage("失败","500",null);

        }

        return new GetMessage("成功","200",code+"/"+lastCode);
    }

    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/selectisgree")
    public GetMessage selectisgree ( String userId, String appId, String trainingId,String code){
        //String userId=token;
        CodeHistory codeHistory=codeHistoryService.selectByCodeInfo(code);
        if(codeHistory==null){
            return new GetMessage("没有该数据","500","");
        }
        if(codeHistory.getAppid().equals(appId)&&codeHistory.getTrainingid().equals(trainingId)&&codeHistory.getUserid().equals(userId)){
            return new GetMessage("成功","200",true);
        }
        return new GetMessage("成功","200",false);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/makecode")
    public GetMessage makecode ( String appId, Integer ruleId){
        String code=codeHistoryService.make(null,appId,null,ruleId,null,null);
        return new GetMessage("成功","200",code);
    }

    public static String generateRandomNumber(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("Number of digits must be greater than 0");
        }

        Random random = new Random();
        StringBuilder result = new StringBuilder();

        // 确保第一个数字不是0
        result.append(random.nextInt(9) + 1);

        // 生成剩余的 n-1 位
        for (int i = 1; i < n; i++) {
            result.append(random.nextInt(10));
        }

        return result.toString();
    }


}
